# -*- coding: utf-8 -*-
# @Time    : 2023/4/29 17:12
# @Author  : Garnetsky
# @FileName: models.py
# @Software: PyCharm
# @Cnblogs ：http://blog.xroot.top
import os
import sys

import django
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "graduate_back.settings")
django.setup()  # 在此环境下操作django=

from main.models import CarsObject, User

"""小车上线"""
def bootCarObject(sid):
    if not CarsObject.objects.filter(id=sid).exists():
        car = CarsObject.objects.create(id=sid, status=True)
        car.save()
        print("创建")
    else:
        car = CarsObject.objects.get(id=sid)
        print("存在")
        car.status = True  # TODO 设备状态为离线暂未实现 tcp心跳检测功能
        car.save()


"""小车下线"""
def existCarObject(sid,userid=None):
    car = CarsObject.objects.filter(id=sid).first()
    if car:
        car.status = False
        car.num += 1
        if(userid):car.user = User.objects.filter(id=userid).first()
        car.save()


"""设备端断开连接"""
def devExit(sid):
    print("操作数据库让小车下线")
    car = CarsObject.objects.filter(id=sid).first()
    if car:
        car.status = True
        car.user = None
        car.save()


""" 小车实时数据更新 """
def carStatusUpdate(data):
    car_id = data['sid']
    car_power = data['power']
    car = CarsObject.objects.get(id=car_id)
    if car:
        car.power = car_power
        car.save()

